<!--
  - Copyright (C) 2018-2019
  - All rights reserved, Designed By www.joolun.com
  - 注意：
  - 本软件为www.joolun.com开发研制，未经购买不得使用
  - 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
  - 一经发现盗用、分享等行为，将追究法律责任，后果自负
-->
<template>
	<view>
		<cu-custom :bgColor="'bg-'+theme.backgroundColor" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">订单确认</block>
		</cu-custom>
		<view class="margin-bottom-bar">
			<view class="cu-list cu-card menu-avatar">
				<view class="cu-item padding-left delivery-way">
					<radio-group @change="deliveryWayChange">
						<radio class="red margin-right-xs" :class="orderSubParm.deliveryWay=='1'?theme.backgroundColor+' checked':''"  :checked="orderSubParm.deliveryWay=='1'?true:false" value="1"></radio>普通快递
						<radio class="red margin-left-sm margin-right-xs" :class="orderSubParm.deliveryWay=='2'?theme.backgroundColor+' checked':''"  :checked="orderSubParm.deliveryWay=='2'?true:false"  value="2"></radio>上门自提
					</radio-group>
				</view>
				<view class="padding-lr">
					<navigator v-if="orderSubParm.deliveryWay == '1'" class="bg-white padding-sm radius flex align-center" url="/pages/user/user-address/list/index?select=true">
						<view class="cu-avatar round cuIcon-locationfill bg-orange"></view>
						<view class="content margin-lr" style="width: 76%;" v-if="userAddress&&userAddress.userName">
							<view class="flex align-center">
								<view class="text-black text-lg">{{userAddress.userName}}</view>
								<view class="text-gray text-df margin-left-sm">{{userAddress.telNum}}</view>
							</view>
							<view class="text-gray text-sm overflow-2 margin-top-xs">
								<view class="cu-tag df bg-green radius margin-right-xs text-xs" v-if="userAddress.isDefault == '1'">默认</view>
								<text>{{userAddress.provinceName}}{{userAddress.cityName}}{{userAddress.countyName}}{{userAddress.detailInfo}}</text>
							</view>
						</view>
						<view class="content loc-content" v-else>请选择收货地址</view>
						<view class="action">
							<text class="cuIcon-right text-gray"></text>
						</view>
					</navigator>
				</view>
			</view>
			<view class="cu-card" v-for="(shopInfo, shopIndex) in shopInfoShoppingCartData" :key="shopInfo.id">
				<view class="cu-item padding">
					<navigator v-if="theme.showType!=2"  hover-class="none" :url="'/pages/shop/shop-detail/index?id=' + shopInfo.id">
						<view class="cu-avatar sm radius" :style="'background-image:url(' + shopInfo.imgUrl + ')'"></view>
						<text class="text-black margin-left-sm">{{shopInfo.name}}</text>
						<text class="cuIcon-right text-gray text-sm"></text>
					</navigator>
					<view class="margin-top" v-for="(item, index) in shopInfo.orderConfirmData" :key="index">
						<view class="flex flex-wrap align-center">
							<image :src="item.picUrl ? item.picUrl : '/static/public/img/no_pic.png'" mode="aspectFill" class="row-img basis-3"></image>
							<view class="desc block basis-7 padding-left-sm">
								<view class="text-black text-df overflow-2">{{item.spuName}}</view>
								<text class="text-gray text-sm margin-top-xs overflow-2" v-if="item.specInfo">{{item.specInfo}}</text>

                <view class="flex justify-between align-center margin-bottom-xs">
                  <view class="text-price text-gray text-sm ">{{item.salesPrice}}</view>
                  <view class="text-gray text-sm ">x{{item.quantity}}</view>
                </view>
                <view v-if="item.paymentCouponPrice" class="text-red text-sm ">优惠金额 <text  class="margin-left-xs text-price  text-red ">{{item.paymentCouponPrice}}</text></view>
                <view v-if="item.paymentPointsPrice" class="text-red text-sm ">积分抵扣 <text  class="margin-left-xs text-price  text-red ">{{item.paymentPointsPrice}}</text></view>
                <view class="text-red text-sm ">支付金额 <text  class="margin-left-xs text-price  text-red ">{{item.paymentPrice}}</text></view>
							</view>
						</view>
					</view>
					<view>
						<view class="cu-bar flex response margin-top" style="min-height: 60upx;">
							<view class="flex-sub">
								<text class="text-gray text-df">运费金额</text>
							</view>
							<view class="flex-twice text-df text-right margin-right-sm">
								<view class="text-price text-red">{{shopInfo.freightPrice}}</view>
							</view>
						</view>
						<view class="cu-bar flex response" style="min-height: 60upx;">
							<view class="flex-sub">
								<view class="text-gray text-df">优惠券</view>
							</view>
							<view class="flex-sub text-df">
								<text class="text-gray" v-if="!shopInfo.couponUser">{{shopInfo.couponUserList.length > 0 ? '有可用优惠券' : '无可用优惠券'}}</text>
								<text class="text-gray" v-if="shopInfo.couponUser">{{shopInfo.couponUser.name}}</text>
							</view>
							<view class="flex-sub text-df text-orange text-right">
								<view v-if="shopInfo.couponUserList.length > 0" @tap="showModalCoupon(shopInfo)">{{shopInfo.totalCouponDeductPrice > 0 ? '优惠￥' + shopInfo.totalCouponDeductPrice :'选择券'}}<text
										class="cuIcon-right margin-right-sm"></text>
								</view>
							</view>
						</view>

						<view class="cu-bar flex response" style="min-height: 60upx;">
							<view class="flex-sub">
								<text class="text-gray text-df">积分抵扣</text>
							</view>
							<view class="flex-twice text-df text-right margin-right-sm">
								<text v-show="totalPointsDeductPrice > 0&&!(
								shopInfo.salesPrice - shopInfo.totalCouponDeductPrice >= pointsConfig.premiseAmount)" class="text-df text-red">满{{pointsConfig.premiseAmount}}可用</text>
								<text v-show="totalPointsDeductPrice > 0 &&
								shopInfo.salesPrice - shopInfo.totalCouponDeductPrice >= pointsConfig.premiseAmount " class=" text-red">-
									<text class="text-price">{{shopInfo.prointPrice}}</text>
								</text>
								<text class=" text-red" :class="totalPointsDeductPrice==0?'text-price':''">{{totalPointsDeductPrice == 0 ? 0:''}}</text>
							</view>
						</view>
						<view class="cu-bar flex response" style="min-height: 60upx;">
							<view class="flex-sub">
								<view class="text-gray text-df">备注</view>
							</view>
							<view class="flex-twice text-df">
								<view class="cu-item align-start text-sm">
									<input @input="userMessageInput" placeholder="给卖家留言" style="font-size: 12px;"></input>
								</view>
							</view>
						</view>
						<view class="cu-bar flex response" style="min-height: 60upx;" v-show="orderSubParm.deliveryWay==2">
							<view class="flex-sub">
								<view class="text-gray text-df">自提地址</view>
							</view>
							<view class="flex-twice text-df">
								<view class="cu-item align-start">
									<text class="text-sm text-gray">{{shopInfo.address}}</text>
								</view>
							</view>
						</view>
						<view class="flex justify-end margin-top-xs margin-right-sm">
							<view class=" text-df text-sm">
								<text class="text-gray text-sm">共{{shopInfo.quantity}}件</text>
								<text class="margin-left-xs text-sm">小计：</text>
								<text class="text-price text-xl text-bold text-red">{{shopInfo.paymentPrice}}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 		<view class="cu-card article mar-top-30">
                        <view class="cu-item">
                            <view class="cu-list menu">
                                <view class="cu-item margin-top-sm">
                                  <view >
                                    <text class="text-grey">订单金额</text>
                                  </view>
                                  <view class="action">
                                    <view class="text-price">{{salesPrice}}</view>
                                  </view>
                                </view> -->
			<!--
                <view class="cu-item" v-if="totalCouponDeductPrice > 0">
                  <view class="content">
                    <text class="text-grey">优惠券抵扣</text>
                  </view>
                  <view class="action text-red">-<text class="text-price">{{totalCouponDeductPrice}}</text></view>
                </view> -->
			<!-- <view class="cu-item" v-if="totalPointsDeductPrice > 0">
                <view >
                    <text class="text-grey">积分抵扣</text>
                </view>
                <view class="action text-red">-<text class="text-price">{{totalPointsDeductPrice}}</text>
                </view>
            </view>
        </view>
    </view>
</view> -->
			<view class="cu-card mar-top-30 ">
				<view class="cu-item bg-white" v-if="totalPointsDeduct > 0">
					<view class="cu-bar flex response">
						<view class="flex-sub text-df">
							<view class="text-gray margin-left-sm">积分</view>
						</view>
						<view class="flex-treble text-sm">
							<text class="text-black" v-if="pointsConfig.premiseAmount <= salesPrice">共{{userInfo.pointsCurrent}}，可用{{totalPointsDeduct}}抵{{totalPointsDeductPriceTemp}}元</text>
							<text class="text-black" v-else>共{{userInfo.pointsCurrent}}，订单满{{pointsConfig.premiseAmount}}元可使用</text>
						</view>
						<view class="flex-sub text-df text-gray text-right margin-right-sm">
							<checkbox-group @change="pointsCheckedChange"
											v-show="pointsConfig.premiseAmount <= salesPrice && userInfo.pointsCurrent >= totalPointsDeduct
									&&((salesPrice-totalPointsDeductPriceTemp)>=0)">
								<checkbox class="red round " :class="totalPointsDeductPrice > 0?theme.themeColor+' checked':''"
										  value="true" :checked="totalPointsDeductPrice > 0"></checkbox>
							</checkbox-group>
						</view>
					</view>
				</view>
				<!-- 用来保证底部高度 -->
				<view v-else class="cu-tabbar-height"></view>
				<view class="cu-tabbar-height"></view>
			</view>
		</view>
		<view class="cu-bar bg-white border foot">
			<view class="flex response">
				<view class="flex-sub"></view>
				<view class="flex-treble bar-rt text-right margin-right-xs">
					<text class="text-sm text-gray">共{{ orderConfirmData.length }}件，</text>
					<text class="text-sm text-gray">合计：</text>
					<text class="text-xl text-bold text-red text-price">{{numberUtil.numberAddition(paymentPrice,freightPrice)}}</text>
					<button class="cu-btn round shadow-blur lg margin-left-sm" :class="'bg-'+theme.themeColor" @tap="orderSub" :loading="loading" :disabled="loading" type>提交订单</button>
				</view>
			</view>
		</view>

		<view :class="'cu-modal bottom-modal ' + modalCoupon" @tap="hideModalCoupon" >
			<view class="cu-dialog bg-white" @tap.stop>
				<view class="">
					<view class="text-lg text-center padding">优惠券</view>
					<scroll-view scroll-y scroll-with-animation style="max-height: 70vh;">
						<checkbox-group class="block" >
							<view class="cu-item padding flex flex-wrap" v-for="(item, index) in shopInfo.couponUserList" :key="index">
								<coupon-user-info class="basis-xl" :couponUserInfo="item" :toUse="false"></coupon-user-info>
								<checkbox
										v-if="numberUtil.numberSubtract(shopInfo.salesPrice, item.premiseAmount)>=0"
										@click="onCoupon(index)" class='round red  text-center vertical-center padding-left'
										:class="index==shopInfo.couponUserIndex?'checked':''"
										:checked="index==shopInfo.couponUserIndex?true:false" :value="index"></checkbox>
								<text
										class="text-red text-sm response text-center cuIcon-warn margin-xs"
										v-if="numberUtil.numberSubtract(shopInfo.salesPrice, item.premiseAmount)<0">订单金额未满¥{{item.premiseAmount}}，无法使用</text>
							</view>
						</checkbox-group>
					</scroll-view>
					<view class=" padding">
						<button class="cu-btn response lg"  :class="'bg-'+theme.themeColor" @tap="hideModalCoupon">确定</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	/**
	 * Copyright (C) 2018-2019
	 * All rights reserved, Designed By www.joolun.com
	 * 注意：
	 * 本软件为www.joolun.com开发研制，未经购买不得使用
	 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
	 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
	 */
	const app = getApp();
	import api from 'utils/api'
	import numberUtil from 'utils/numberUtil.js'
	import couponUserInfo from "@/components/coupon-user-info/index";

	export default {
		data() {
			return {
				CustomBar: this.CustomBar,
				theme: app.globalData.theme, //全局颜色变量
				numberUtil: numberUtil,
				shopInfo: {
					couponUserList: [],
					couponUserIndex: -1
				}, // 当前店铺信息及其包含的订单信息，用于优惠券计算等。
				shopInfoShoppingCartData: [], //店铺格式的数据
				orderConfirmData: [],
				salesPrice: 0,
				paymentPrice: 0,
				freightPrice: 0,
				userAddress: {},
				orderSubParm: {
					deliveryWay: '1'
				},
				loading: false,
				userInfo: {},
				pointsConfig: {
					premiseAmount: 0
				},
				totalPointsDeduct: 0,//可用积分
				totalPointsDeductPriceTemp: 0,//积分可抵的金额
				totalPointsDeductPrice: 0, //积分可抵金额，勾选时有值
				modalCoupon: '',
				spuIds: [],
				couponUser: null,
				totalCouponDeductPrice: 0, //优惠券总价格
				pointsCheckedValue: null,
				couponCheckedValue: null,
				temp: "",
				freightMap: new Map() //各运费模块计数
			};
		},
		components: {
			couponUserInfo
		},
		props: {},
		onShow() {
		},
		onLoad: function() {
			this.numberUtil = numberUtil;
			this.userAddressPage();
			this.pointsConfigGet();
			this.userInfoGet();
			this.orderConfirmDo();
		},
		methods: {
			// 订单提交成功后处理
			orderSubAfter(data) {
				let that = this
				// #ifdef MP-WEIXIN
				//微信小程序订阅消息
				api.wxTemplateMsgList({
					enable: '1',
					useTypeList: ['2', '3']
				}).then(res => {
					let tmplIds = [];
					res.data.forEach(item => {
						tmplIds.push(item.priTmplId);
					});
					uni.requestSubscribeMessage({
						tmplIds: tmplIds,
						success(res) {
							console.log(res);
						},
						complete() {
							that.toOrderPage(data)
						}

					});
				});
				// #endif
				// #ifndef MP-WEIXIN
				//非微信小程序
				this.toOrderPage(data)
				// #endif
			},
			toOrderPage(data){
				if(data.length > 1){//订单被拆分，跳订单列表页
					uni.redirectTo({
						url: '/pages/order/order-list/index?status=0'
					});
				}else if(data.length == 1){//跳订单详情页
					uni.redirectTo({
						url: '/pages/order/order-detail/index?callPay=true&id=' + data[0].id
					});
				}
			},
			deliveryWayChange(e) {
				this.orderSubParm.deliveryWay = e.detail.value;
				this.freightMap = new Map();
				// this.orderConfirmDo();
				let shopInfos = this.shopInfoShoppingCartData;
				//重新计算快递费
				let salesPrice = 0; //订单金额
				let paymentPrice = 0; //支付金额
				let that = this;
				shopInfos.forEach(function(shopInfo) { //遍历店铺信息
					let freightPrice = 0; //运费
					let moneyTotal = 0; //总额
					let shopInfoSalesPrice = 0; //总额
					shopInfo.orderConfirmData.forEach(function(orderConfirm) { //所有商品信息
						let freightTemplat = orderConfirm.freightTemplat;
						if (freightTemplat&&that.orderSubParm.deliveryWay != '2') {//自提不算运费
							if (freightTemplat.type == '1') {
								//模板类型1、买家承担运费
								let quantity = orderConfirm.quantity;
								if (freightTemplat.chargeType == '1') {
									//1、按件数；
									that.countFreight(orderConfirm, freightTemplat, quantity);
								} else if (freightTemplat.chargeType == '2') {
									//2、按重量
									let weight = orderConfirm.weight;
									that.countFreight(orderConfirm, freightTemplat, (weight * quantity));
								} else if (freightTemplat.chargeType == '3') {
									//3、按体积
									let volume = orderConfirm.volume;
									that.countFreight(orderConfirm, freightTemplat, (volume * quantity));
								}
							} else {
								orderConfirm.freightPrice = 0;
							}
						} else {
							orderConfirm.freightPrice = 0;
						}
						salesPrice = (Number(salesPrice) + (orderConfirm.salesPrice * orderConfirm.quantity) + Number(orderConfirm.freightPrice));
						shopInfoSalesPrice = (Number(shopInfoSalesPrice)+(orderConfirm.salesPrice * orderConfirm.quantity) +  Number(orderConfirm.freightPrice));
						let paymentPrice = (orderConfirm.salesPrice * orderConfirm.quantity);
						if(orderConfirm.paymentCouponPrice){ //表示有优惠券
							let paymentPriceT = paymentPrice - Number(orderConfirm.paymentCouponPrice); //减去优惠券抵扣的金额
							if(paymentPriceT>0){//减去的金额后必须大于0
								paymentPrice = paymentPriceT
							}else{

							}
						}
						if(orderConfirm.paymentPointsPrice){ //表示有积分抵扣
							let paymentPriceT = paymentPrice - Number(orderConfirm.paymentPointsPrice); //减去积分抵扣的金额
							if(paymentPriceT>0){//减去的金额后必须大于0
								paymentPrice = paymentPriceT
							}else{

							}
						}
						orderConfirm.paymentPrice = Number(paymentPrice).toFixed(2);
						//计算运费
						freightPrice = (Number(freightPrice) + Number(orderConfirm.freightPrice));
						moneyTotal = moneyTotal + Number(paymentPrice) + Number(orderConfirm.freightPrice);
					});
					shopInfo.salesPrice = Number(shopInfoSalesPrice).toFixed(2);
					shopInfo.paymentPrice = Number(moneyTotal).toFixed(2);
					shopInfo.freightPrice = Number(freightPrice).toFixed(2);
					paymentPrice = paymentPrice + moneyTotal;

				});
				this.salesPrice = Number(salesPrice).toFixed(2);
				this.paymentPrice = Number(paymentPrice).toFixed(2);
				if (this.pointsCheckedValue) {
					this.pointsCheckedChange({
						detail: {
							value: this.pointsCheckedValue
						}
					});
				}

			},

			orderConfirmDo() {
				// 本地获取参数信息
				let that = this;
				uni.getStorage({
					key: 'param-orderConfirm',
					success: function(res) {
						let orderConfirmData = res.data;
						let shopInfos = []; //调整好店铺格式后的数据
						let shopInfoIds = []; //店铺ID

						let salesPrice = 0; //订单金额
						let totalPointsDeduct = 0; //最多可用积分数
						let totalPointsDeductPriceTemp = 0; //最多可用积分数抵扣金额
						let spuIds = null;
						orderConfirmData.forEach((orderConfirm, index) => {
							if (shopInfoIds.indexOf(orderConfirm.shopInfo.id) === -1) {
								shopInfoIds.push(orderConfirm.shopInfo.id); //保存店铺信息ID
								let shopInfoTemp = JSON.parse(JSON.stringify(orderConfirm.shopInfo));
								shopInfoTemp.orderConfirmData = []; //用来存储店铺的商品信息
								shopInfos.push(shopInfoTemp); //保存店铺信息
							}
						});
						shopInfos.forEach(function(shopInfo) { //遍历店铺信息
							let moneyTotal = 0; //店铺商品小计总额
							let prointPrice = 0; //店铺商品小计积分抵扣总额
							let quantityTotal = 0; //店铺商品小计数量
							let freightPrice = 0; //运费
							shopInfo.couponUserList = [];
							shopInfo.couponUser = null;
							orderConfirmData.forEach(function(orderConfirm) { //所有商品信息
								if (orderConfirm.shopInfo && shopInfo.id === orderConfirm.shopInfo.id) {
									if (spuIds) {
										spuIds = spuIds + ',' + orderConfirm.spuId;
									} else {
										spuIds = orderConfirm.spuId;
									}
									let freightTemplat = orderConfirm.freightTemplat;
									if (freightTemplat&&that.orderSubParm.deliveryWay != '2') {//自提不算运费
										if (freightTemplat.type == '1') {
											//模板类型1、买家承担运费
											let quantity = orderConfirm.quantity;
											if (freightTemplat.chargeType == '1') {
												//1、按件数；
												that.countFreight(orderConfirm, freightTemplat, quantity);
											} else if (freightTemplat.chargeType == '2') {
												//2、按重量
												let weight = orderConfirm.weight;
												that.countFreight(orderConfirm, freightTemplat, (weight * quantity));
											} else if (freightTemplat.chargeType == '3') {
												//3、按体积
												let volume = orderConfirm.volume;
												that.countFreight(orderConfirm, freightTemplat, (volume * quantity));
											}
										} else {
											orderConfirm.freightPrice = 0;
										}
									} else {
										orderConfirm.freightPrice = 0;
									}
									salesPrice = ((salesPrice) + orderConfirm.salesPrice * orderConfirm.quantity + Number(orderConfirm.freightPrice));
									orderConfirm.paymentPrice = (orderConfirm.salesPrice * orderConfirm.quantity ).toFixed(2);
									//计算运费
									freightPrice = ((freightPrice) + Number(orderConfirm.freightPrice));
									//计算积分抵扣
									if (orderConfirm.pointsDeductSwitch == '1') {//如果此商品可以用积分抵扣
										// 商品可抵扣的积分金额 = 商品价格 * 积分可抵扣的比例 * 100% *  数量
										let pointsDeductPrice = Math.floor(orderConfirm.salesPrice * (orderConfirm.pointsDeductScale / 100) * orderConfirm.quantity);
										prointPrice = prointPrice + pointsDeductPrice;
										// 商品可抵扣的金额的具体积分 = 商品可抵扣的金额 / 每积分可抵扣的比例
										let pointsDeduct = pointsDeductPrice / orderConfirm.pointsDeductAmount;
										orderConfirm.paymentPointsPrice2 = pointsDeductPrice;
										// 抵扣积分后的支付金额
										orderConfirm.paymentPrice2 = (orderConfirm.salesPrice * orderConfirm.quantity).toFixed(2) - pointsDeductPrice;
										// 抵扣的积分金额不能小于1
										if (pointsDeductPrice >= 1) {
											orderConfirm.paymentPoints2 = pointsDeduct;
											totalPointsDeductPriceTemp = Number(totalPointsDeductPriceTemp) + Number(pointsDeductPrice);
											totalPointsDeduct = Number(totalPointsDeduct) + Number(pointsDeduct);
										}
									}
									quantityTotal = quantityTotal + orderConfirm.quantity;
									moneyTotal = moneyTotal + (orderConfirm.salesPrice * orderConfirm.quantity) + Number(orderConfirm.freightPrice);
									shopInfo.orderConfirmData.push(orderConfirm);
								}
							});
							shopInfo.prointPrice = prointPrice.toFixed(2);
							shopInfo.salesPrice = moneyTotal.toFixed(2);
							shopInfo.paymentPrice = moneyTotal.toFixed(2);
							shopInfo.quantity = quantityTotal;
							shopInfo.freightPrice = freightPrice.toFixed(2);
							shopInfo.totalCouponDeductPrice = 0;//优惠券金额
						});
						that.shopInfoShoppingCartData = shopInfos; //调整好店铺格式后的数据
						that.orderConfirmData = orderConfirmData;
						that.salesPrice = salesPrice.toFixed(2);
						// that.paymentPrice = salesPrice - totalPointsDeductPriceTemp;
						that.paymentPrice = salesPrice.toFixed(2);
						that.totalPointsDeduct = totalPointsDeduct;
						that.totalPointsDeductPriceTemp = totalPointsDeductPriceTemp;
						that.spuIds = spuIds;

						if (that.pointsCheckedValue) {
							that.pointsCheckedChange({
								detail: {
									value: that.pointsCheckedValue
								}
							});
						}
						that.couponUserPage(); //查询优惠券

					}
				});
			},

			//计算运费
			countFreight(orderConfirm, freightTemplat, quantity) {
				let freightMap = this.freightMap
				let freightMapValue = 0
				if (freightMap.has(freightTemplat.id)) {
					freightMapValue = freightMap.get(freightTemplat.id)
				}
				quantity = quantity + freightMapValue
				freightMap.set(freightTemplat.id, quantity)
				this.freightMap = freightMap
				let firstNum = freightTemplat.firstNum;
				let firstFreight = freightTemplat.firstFreight;
				let continueNum = freightTemplat.continueNum;
				let continueFreight = freightTemplat.continueFreight;

				if (quantity <= firstNum) {
					//首件之内数量
					orderConfirm.freightPrice = firstFreight;
					if (freightMapValue > 0) { //同一运费模板已有商品算了运算，并在首件之内，当前商品不算运费
						orderConfirm.freightPrice = 0
					}
				} else {
					//首件之外数量
					let num = quantity - firstNum;
          let val1 = continueNum > 0 ? num / continueNum : 0//不能为0
					orderConfirm.freightPrice = (Number(firstFreight) + Math.ceil(val1) * continueFreight).toFixed(2);
					if (freightMapValue > 0) { //同一运费模板已有商品算了运算，并超过了首件数量，当前商品只算超出运费
						if (freightMapValue >= firstNum) {
							num = quantity - freightMapValue - (freightMapValue - firstNum) % continueNum
						} else {
							num = quantity - freightMapValue - (firstNum - freightMapValue)
						}
            let val2 = continueNum > 0 ? num / continueNum : 0//不能为0
						orderConfirm.freightPrice = (Math.ceil(val2) * continueFreight).toFixed(2)
					}
				}
			},
			setUserAddress(obj) {
				this.userAddress = obj;
			},
			//获取默认收货地址
			userAddressPage() {
				api.userAddressPage({
					searchCount: false,
					current: 1,
					size: 1,
					isDefault: '1'
				}).then(res => {
					let records = res.data.records;
					if (records && records.length > 0) {
						this.userAddress = records[0];
					}
				});
			},

			//获取积分设置
			pointsConfigGet() {
				api.pointsConfigGet().then(res => {
					if(res.data){
						this.pointsConfig = res.data
					}
				});
			},

			//获取商城用户信息
			userInfoGet() {
				api.userInfoGet().then(res => {
					this.userInfo = res.data;
				});
			},

			userMessageInput(e) {
				this.orderSubParm.userMessage = e.detail.value;
			},

			//提交订单
			orderSub() {
				let that = this;
				let userAddress = this.userAddress;
				if (this.orderSubParm.deliveryWay == '1' && (userAddress == null || !userAddress.userName)) {
					uni.showToast({
						title: '请选择收货地址',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				this.loading = true;
				this.orderSubParm.skus = that.orderConfirmData;
				api.orderSub(Object.assign({}, {
					userAddressId: that.orderSubParm.deliveryWay == '1' ? userAddress.id : null
				}, this.orderSubParm)).then(res => {
					that.orderSubAfter(res.data);
				}).catch(() => {
					this.loading = false;
				});
			},

			//选择使用积分
			pointsCheckedChange(e) {
				if (e.detail.value == 'true') {
					let orderConfirmData = this.orderConfirmData;
					let that = this;
					orderConfirmData.forEach(function(orderConfirm) {
						if (orderConfirm.pointsDeductSwitch == '1') {//表示该商品能够使用积分抵扣金额
							let paymentPrice = Number(orderConfirm.paymentPrice2);// 抵扣积分后的支付金额
							if(orderConfirm.paymentCouponPrice){ // 表示有优惠券
								paymentPrice = paymentPrice - Number(orderConfirm.paymentCouponPrice); //减去优惠券抵扣的金额
							}
							orderConfirm.paymentPoints = orderConfirm.paymentPoints2;
							orderConfirm.paymentPointsPrice = orderConfirm.paymentPointsPrice2;
							orderConfirm.paymentPrice = paymentPrice.toFixed(2);
						}
					});
					this.pointsCheckedValue = e.detail.value;
					this.totalPointsDeductPrice = this.totalPointsDeductPriceTemp;
					this.orderConfirmData = orderConfirmData;
				} else {
					let orderConfirmData = this.orderConfirmData;
					let that = this;
					orderConfirmData.forEach(function(orderConfirm) {
						if (orderConfirm.pointsDeductSwitch == '1') {
							let paymentPrice = orderConfirm.salesPrice * orderConfirm.quantity;//总金额
							if(orderConfirm.paymentCouponPrice && Number(orderConfirm.paymentCouponPrice)>0){ //表示已勾选积分抵扣金额
								paymentPrice = paymentPrice - Number(orderConfirm.paymentCouponPrice); //减去优惠券抵扣的金额
							}
							orderConfirm.paymentPrice = paymentPrice.toFixed(2);
							orderConfirm.paymentPoints = 0;
							orderConfirm.paymentPointsPrice = 0;
						}
					});
					this.pointsCheckedValue = e.detail.value;
					this.totalPointsDeductPrice = 0;
					this.orderConfirmData = orderConfirmData;
				}
				this.setPaymentPrice();//重新计算金额
			},

			//查询可用电子券
			couponUserPage() {
				api.couponUserPage({
					searchCount: false,
					current: 1,
					size: 50,
					descs: 'create_time',
					spuIds: this.spuIds
				}).then(res => {
					if (res.data.records && res.data.records.length > 0) {
						this.shopInfoShoppingCartData.forEach(shopInfo => {
							let items = [];
							let supIds = [];//用来去重
							res.data.records.forEach(item => { //取出每个店铺的优惠券
								if (shopInfo.id == item.shopId && supIds.indexOf(item.id)===-1) {
									items.push(item);
									supIds.push(item.id);
								}
							})
							shopInfo.couponUserList = items;
						});
					}
				});
			},

			showModalCoupon(shopInfo) {
				this.shopInfo = {
					couponUserList: [],
					couponUserIndex: ''
				};
				this.shopInfo = shopInfo;
				this.modalCoupon = 'show';
			},

			hideModalCoupon() {
				this.modalCoupon = '';
			},
			onCoupon(index) {
			  // 选择优惠券时先取消积分的选择
        this.pointsCheckedChange({
          detail: {value:false}
        })
				if(index==this.shopInfo.couponUserIndex){//
					this.shopInfo.couponUserIndex = -1;
					// 计算优惠金额
					this.shopInfo.orderConfirmData.map(item=>{
						item.paymentPrice = item.salesPrice.toFixed(2);
						item.paymentCouponPrice=0;
						item.couponUserId = '';
					})
					this.shopInfo.totalCouponDeductPrice = 0;
					this.shopInfo.couponUser = null
					this.setPaymentPrice();
				} else {
					this.shopInfo.couponUserIndex = index
					this.couponUserChange(index);
				}
			},
			//金额使用优惠券检验
			paymentPriceValid(orderConfirmt, couponUser){
				let orderConfirmT =JSON.parse(JSON.stringify(orderConfirmt));
				this.setPaymentCouponPrice(orderConfirmT, couponUser);
				// 判断优惠后金额是否大于0
				if(orderConfirmT.paymentPrice<0){
					return false
				}
				return true
			},
			//选择电子券:选择券后积分抵扣自动重新计算
			couponUserChange(index) {
				uni.showLoading()
				let couponUser = index > -1 ? this.shopInfo.couponUserList[index] : null;
				let orderConfirmData = this.shopInfo.orderConfirmData; //计算优惠金额
				orderConfirmData.map(item=>{
				  item.paymentCouponPrice=0;// 先将之前的代金券的金额变为0后再赋值
        })
				let orderConfirmSrc = null
				let indexGoods = -1
				// this.shopInfo.totalCouponDeductPrice =  0
				if (couponUser && couponUser.suitType == '1') {
					//1、全部商品适用，默认优惠第一个商品，如果第一个商品金额优惠后小于0那么不能进行优惠，然后依次继续算第二个商品
					for (var i = 0; i < orderConfirmData.length; i++) {
						orderConfirmSrc = orderConfirmData[i]
						let isOk = this.paymentPriceValid(orderConfirmSrc, couponUser)
						if(isOk){
							indexGoods = i
							this.setPaymentCouponPrice(orderConfirmSrc, couponUser);
							break //如果有跳出循环
						}
					}
					// let orderConfirm = orderConfirmData[0]
					// let isOk = this.paymentPriceValid(orderConfirm, couponUser)
					// if(isOk){
					// 	this.setPaymentCouponPrice(orderConfirm, couponUser);
					// }
					if(orderConfirmSrc&&indexGoods>-1){
						this.shopInfo.orderConfirmData[indexGoods] = orderConfirmSrc;
						this.shopInfo.totalCouponDeductPrice = orderConfirmSrc.paymentCouponPrice;
					}else{
						this.shopInfo.couponUserIndex = -1
						uni.showToast({
							title: '选择优惠券失败，商品金额小于优惠券金额',
							icon: 'none',
							duration: 3000
						});
					}
				} else if (couponUser && couponUser.suitType == '2') {
					//2、指定商品可用，默认优惠第一个指定商品,如果商品金额小于优惠券金额，依次取下面的
					try {
						for (var i = 0; i < orderConfirmData.length; i++) {
							orderConfirmSrc = orderConfirmData[i]
							if (orderConfirmSrc.spuId == couponUser.goodsSpu.id){
								let isOk = this.paymentPriceValid(orderConfirmSrc, couponUser)
								if(isOk){
									indexGoods = i
									this.setPaymentCouponPrice(orderConfirmSrc, couponUser);
									break //如果有跳出循环
								}
							}
						}
						if(orderConfirmSrc&&indexGoods>-1){//
							this.shopInfo.orderConfirmData[indexGoods] = orderConfirmSrc;
							this.shopInfo.totalCouponDeductPrice = orderConfirmSrc.paymentCouponPrice;
						}else{
							this.shopInfo.couponUserIndex = -1
							uni.showToast({
								title: '选择优惠券失败，商品金额小于优惠券金额',
								icon: 'none',
								duration: 3000
							});
						}

						// orderConfirmData.forEach((orderConfirm) => {
						// 	if (orderConfirm.spuId == couponUser.goodsSpu.id) {
						// 		orderConfirmSrc = orderConfirm
						// 		this.setPaymentCouponPrice(orderConfirm, couponUser);
						// 		this.shopInfo.totalCouponDeductPrice = orderConfirm.paymentCouponPrice;
						// 		throw "";
						// 	}
						// });
					} catch (e) {}
					this.shopInfo.orderConfirmData = orderConfirmData;
				}
				if(indexGoods>-1){//
					this.shopInfo.couponUser = couponUser
				}else{
					this.shopInfo.couponUser = null
				}
				// 计算积分抵扣的
				if(this.totalPointsDeductPrice>0){
					this.pointsCheckedChange({detail: { value: ['true'] }})
				}else{
					this.setPaymentPrice();
				}
				uni.hideLoading()
			},
			setPaymentPrice(){//计算总额
				let that = this;
				let paymentPrice = 0;//减去积分后的金额
				let salesPrice = 0;//不减积分的金额
				let totalCouponDeductPrice = 0;//优惠券金额
				this.shopInfoShoppingCartData.forEach(function(shopInfo){
					// 每个店铺支付的总金额 = 总金额 - 代金券金额
					let shopPaymentPrice = Number(shopInfo.salesPrice) - Number(shopInfo.totalCouponDeductPrice);
					salesPrice = salesPrice + shopPaymentPrice;//总额
					// 总额必须大于设置的积分限额，并且支付的金额大于店铺的积分抵扣金额，并且有积分可以抵扣的金额，paymentPointsPrice
					if(salesPrice>=that.pointsConfig.premiseAmount
							&& shopPaymentPrice - shopInfo.prointPrice >= 0
							&& that.totalPointsDeductPrice>0){
						shopInfo.paymentPrice = (shopPaymentPrice - Number(shopInfo.prointPrice)).toFixed(2);
					}else{
						shopInfo.paymentPrice = shopPaymentPrice.toFixed(2);
					}
					// shopInfo.paymentPrice =
					paymentPrice = Number(paymentPrice) + Number(shopInfo.paymentPrice);
					totalCouponDeductPrice = totalCouponDeductPrice + Number(shopInfo.totalCouponDeductPrice);
				})
				this.salesPrice = salesPrice.toFixed(2);
				// this.paymentPrice = paymentPrice.toFixed(2);
				//支付金额 = 订单总金额 - 积分抵扣金额
				if(this.salesPrice>=this.pointsConfig.premiseAmount){//如果大于才能抵扣积分
					this.paymentPrice = (paymentPrice).toFixed(2);
				} else {
					this.paymentPrice = this.salesPrice;
					if(this.totalPointsDeductPrice>0){ //表示已勾选积分抵扣金额
						this.totalPointsDeductPrice = 0;
					}
				}
				this.totalCouponDeductPrice = totalCouponDeductPrice;
			},
			setPaymentCouponPrice(orderConfirm, couponUser) { //设置优惠券后的价格
				orderConfirm.couponUserId = couponUser.id;
				let salesPrice = orderConfirm.salesPrice * orderConfirm.quantity;
				if (couponUser.type == '1') {
					//代金券
					orderConfirm.paymentPrice = Number(salesPrice - couponUser.reduceAmount).toFixed(2);
					orderConfirm.paymentCouponPrice = couponUser.reduceAmount;//优惠金额
				}else if (couponUser.type == '2') {
					//折扣券
					let paymentCouponPrice = Number(salesPrice * (1 - couponUser.discount / 10)).toFixed(2);
					orderConfirm.paymentPrice = Number(salesPrice - paymentCouponPrice).toFixed(2);
					orderConfirm.paymentCouponPrice = paymentCouponPrice;//优惠金额
				}
			}

		}
	};
</script>
<style>
	.row-img {
		width: 180rpx !important;
		height: 180rpx !important;
		border-radius: 10rpx
	}

	.specification{
		white-space: normal;
		height: auto;
	}

	.loc-content {
		width: calc(100% - 96rpx - 60rpx - 80rpx) !important;
		left: 126rpx !important
	}

	.loc-info {
		line-height: 1.4em
	}

	.cu-list.menu>.cu-item:after {
		border-bottom: unset !important
	}

	.cu-list.menu>.cu-item {
		min-height: unset !important
	}

	.delivery-way {
		justify-content: unset !important
	}
</style>
